<template>
    <div class="user-info">
        <el-container>
            <el-header class="home-header" height="50px">
                <HomeHeader />
            </el-header>
            <el-main class="main" style="margin-top: 45px;">
                <div class="box">
                    <el-row>
                        <el-col :span="6" id="left-box">
                            <div id="avatar">
                                <img id="img" :src="getImage(userInfo.img)" />
                                <div id="txt">
                                    <h3>{{ userInfo.username }}</h3>
                                </div>
                            </div>
                            <hr style="border:1px solid #eee;width:100%;">
                            <ul id="menu">
                                <li style="cursor:pointer" @click="selectIndex = '1'">我的信息</li>
                                <hr style="border:1px solid #eee;width:100%;">
                                <li style="cursor:pointer" @click="selectIndex = '2'">修改密码</li>
                                <hr style="border:1px solid #eee;width:100%;">
                            </ul>
                        </el-col>
                        <el-col :span="17" id="right-box">
                            <h3>我的信息<div style="display: inline;float: right;">IP属地：
                                    <span v-if="userInfo.address == null">未知</span>
                                    <span v-else>{{ userInfo.address }}</span>
                                </div>
                            </h3>
                            <div v-if="selectIndex == '1'"
                                style="width: 100%;height:400px;margin-top: 50px;display:flex">
                                <div v-if="!changeInfo" style="height:400px;width:70%;margin-left:80px">
                                    <ul>
                                        <li>账号 : {{ userInfo.username }}</li>
                                        <li>真名 : {{ userInfo.realName }}</li>
                                        <li>性别 : {{ sexString }}</li>
                                        <li>身份证号 : {{ userInfo.identity }}</li>
                                        <li>地区 : {{ userInfo.address }}</li>
                                        <li><el-button type="primary" @click="changeInfo = true">修改我的信息</el-button></li>
                                    </ul>
                                </div>
                                <div v-if="changeInfo" style="height:400px;width:70%;margin-left:80px;">
                                    <el-form label-width="60px" ref="userFormRef" :model="userForm"
                                        label-position="left" style="padding-left:40px" :rules="userRules">
                                        <el-form-item label="账号">
                                            <el-input v-model="userForm.username" style="width:220px"></el-input>
                                        </el-form-item>
                                        <el-form-item label="性别">
                                            <el-radio-group v-model="userForm.sex">
                                                <el-radio label="男" value="0"></el-radio>
                                                <el-radio label="女" value="1"></el-radio>
                                            </el-radio-group>
                                        </el-form-item>
                                        <el-form-item style="margin-left: 70px;">
                                            <el-button type="primary" @click="editUserInfo">提交</el-button>
                                            <el-button type="warning" @click="changeInfo = false">返回</el-button>
                                        </el-form-item>
                                    </el-form>
                                </div>
                                <div style="width:30%;height:100%" id="img2">
                                    <img :src="getImage(userInfo.img)" style="height: 120px;width:120px;" />
                                    <div class="image-container">
                                        <el-upload class="avatar-uploader" action="#" :http-request="handleFileUpload"
                                            :show-file-list="false" :limit="1" :on-success="handleAvatarSuccess"
                                            :before-upload="beforeAvatarUpload">
                                            修改头像
                                        </el-upload>
                                    </div>
                                </div>
                            </div>
                            <div v-if="selectIndex == '2'" style="margin-top: 50px">
                                <el-form label-width="100px" ref="passFormRef" :model="passForm" label-position="left"
                                    style="padding-left:40px" :rules="passRules">
                                    <el-form-item label="输入原密码">
                                        <el-input v-model="passForm.password" style="width:220px"></el-input>
                                    </el-form-item>
                                    <el-form-item label="输入新密码">
                                        <el-input v-model="passForm.newPass" style="width:220px"></el-input>
                                    </el-form-item>
                                    <el-form-item label="确认新密码">
                                        <el-input v-model="passForm.checkPass" style="width:220px"></el-input>
                                    </el-form-item>
                                    <el-form-item style="margin-left: 70px;">
                                        <el-button type="primary" @click="editUserPass">提交</el-button>
                                        <el-button type="warning" @click="selectIndex = '1'">返回</el-button>
                                    </el-form-item>
                                </el-form>
                            </div>
                        </el-col>
                    </el-row>
                </div>
            </el-main>
        </el-container>
    </div>
</template>


<script lang="ts" setup>
import { me, updateUser } from '@/api';
import HomeHeader from '@/components/HomeHeader.vue';
import { ElMessage, FormInstance, FormRules } from 'element-plus';
import { computed, onMounted, reactive, ref } from 'vue';

const userInfo = reactive({
    username: '',
    realName: '',
    sex: '',
    identity: '',
    address: '',
    img: ''
})

const userForm = reactive({
    username: '',
    sex: '',
})

const passForm = reactive({
    password: '',
    newPass: '',
    checkPass: '',
})

const submitUser=reactive({
    username: '',
    realName: '',
    password:'',
    sex: '',
    identity: '',
    address: '',
    img: ''
})
const selectIndex = ref<'1' | '2' | '3'>('1');
const changeInfo = ref(false);

const userFormRef = ref<FormInstance>()
const passFormRef = ref<FormInstance>()

const reg = /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/;
const sexString = computed(() => {
    return userInfo.sex === '0' ? '男' : '女';
});
const validateName = (rule: any, value: any, callback: any) => {
    if (!reg.test(value)) {
        callback(new Error('昵称长度在2~16字之间，且不包含空格和特殊字符'));
    }
    else {
        callback();
    }
};
const validatePassword = (rule: any, value: any, callback: any) => {
    if (!value.trim()) {
        callback(new Error('密码不能为空'))
    } else {
        if (passForm.checkPass !== '') {
            if (!passFormRef.value) return
            passFormRef.value.validateField('checkPass')
        }
        callback()
    }
};
const validateCheckPassword = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请再次输入密码'));
    }
    else if (value !== passForm.password) {
        callback(new Error('两次输入密码不一致!'));
    }
    else {
        callback();
    }
};
const userRules = reactive<FormRules<typeof userForm>>({
    username: [{ required: true, message: '账号不得为空', trigger: 'blur' }, { validator: validateName, trigger: 'blur' }],
    sex: [{ required: true, message: '请勾选性别', trigger: 'blur' }]
})
const passRules = reactive<FormRules<typeof passForm>>({
    newPass: [{ min: 4, max: 32, message: '密码长度应为4~32字符之间', trigger: 'blur' }, { validator: validatePassword, trigger: 'blur' }],
    checkPass: [{ validator: validateCheckPassword, trigger: 'blur' }],
})


onMounted(() => {
    me().then((resp: { data: any }) => {
        let data = resp.data;
        if (data.code == '50041') {
            Object.assign(userInfo, data.data);
            console.log(data.data);
            Object.assign(submitUser,data.data);
        }
    })
});

const baseURL = ref('http://localhost:8081/common')
//获取图片
const getImage = (img: any) => {
    return baseURL.value + `/download?name=${img}`
}
const imageUrl = ref('') // 用来存储图片URL

const beforeAvatarUpload = (file: any) => {
    const suffix = file.name.split('.')[1]
    const size = file.size / 1024 / 1024 < 10
    if (['png', 'jpeg', 'jpg'].indexOf(suffix) < 0) {
        ElMessage.error('上传图片只支持 png、jpeg、jpg 格式！')
        return false
    }
    if (!size) {
        ElMessage.error('上传文件大小不能超过 10MB!')
        return false
    }
    return true
}

const handleAvatarSuccess = (res: any, file: any) => {
    imageUrl.value = baseURL.value + `/download?name=${res.data}`;
    submitUser.img = res.data
}
const handleFileUpload = (file: any) => {
    editUserInfo
}

const editUserInfo = () => {
    if(userForm.username.trim()!=null){
        submitUser.username=userForm.username
    }
    if(userForm.sex.trim()!=null){
        submitUser.sex=userForm.sex
    }
    updateUser(submitUser).then((resp: { data: any; }) => {
        let data = resp.data;
        if (data.code == '50031') {
            console.log(data);
            ElMessage({
                message: data.message,
                type: 'success'
            });
            setTimeout(() => {
                window.location.reload();
            }, 1000);
        } else {
            console.log(data);
            ElMessage({
                message: data.message,
                type: 'error'
            });
        }
    });
}

const editUserPass = () => {
    submitUser.password=passForm.newPass;
    updateUser(submitUser).then((resp: { data: any; }) => {
        let data = resp.data;
        if (data.code == '50031') {
            console.log(data);
            ElMessage({
                message: data.message,
                type: 'success'
            });
            setTimeout(() => {
                window.location.reload();
            }, 1000);
        } else {
            console.log(data);
            ElMessage({
                message: data.message,
                type: 'error'
            });
        }
    });
}

</script>

<style scoped>
.home-header {
    background-color: #fff;
    position: fixed;
    top: 0;
    width: 100%;
    z-index: 1000;
}

.main {
    background-color: #eee;
    height: 660px;

}

.box {
    display: block;
    height: 600px;
    width: 1000px;
    margin: 0 auto;
    text-align: left;
    overflow: hidden;
    background-color: white;
}

#left-box {
    float: left;
    height: 660px;
    overflow: hidden;

    #img {
        float: left;
        width: 64px;
        height: 64px;
        margin: 12px;
    }

    #txt {
        font-size: 14px;
        line-height: 23px;
        margin-top: 0px;
        width: 100px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    #menu {
        clear: both;
    }

    ul {
        list-style: none;
        padding-left: 0;
        text-align: center;
    }

    li {
        line-height: 34px;
    }
}


#right-box {
    height: 660px;
    overflow: hidden;
    border-left: 10px solid #eee;

    h3 {
        margin: 10px 20px;
        border-bottom: 1px solid;
        font-size: 14px;
        line-height: 30px;
    }

    #img2 {
        float: right;
        line-height: 40px;
        text-align: center;
        width: 124px;
        height: 164px;
    }

    ul {
        list-style: none;

    }

    li {
        margin-bottom: 5px;
        line-height: 34px;
        font-size: 18px;
    }
}

a {
    text-decoration: none;
    color: black;
}

a:hover {
    color: orange;
}
</style>